<template>
  <div>
    <div>
      <div style="display:flex;margin-bottom: 8px; ">
        <div style="flex:1 1 auto;">
        {{mainName}} <ArrowRightOutlined /> {{relaName}}
        </div>
        <div style="flex:0 0 100px;text-align:right;">

        <a-button size="small" type="primary" title="编辑模型" v-if="!canEdit" @click="changeEditType">
          <template #icon>
            <EditOutlined />
          </template>
        </a-button>

        <a-button size="small" type="primary" title="阅读模型" v-if="canEdit"  @click="changeEditType">
          <template #icon >
            <FileMarkdownOutlined />
          </template>
        </a-button>
        </div>
      </div>
      <Editor
        v-if="canEdit"
        v-model:value="v"
        @change="handleChange"
        mode="split"
        :plugins="plugins"
        :uploadImages="uploadImages"
        :editorConfig="editorConfig"
      />
      <div style="margin-top: 8px; text-align: right" >
        <a-button type="primary" size="small" v-if="canEdit" @click="editRelaMd">Save</a-button>
      </div>
    </div>
    <Viewer v-if="!canEdit" :value="v" :plugins="plugins" />
  </div>
</template>

<script setup>
import { ref, onMounted, markRaw, watch } from "vue";

import {PaperClipOutlined, FileMarkdownOutlined,EditOutlined,ArrowRightOutlined} from '@ant-design/icons-vue'
import pmpHooks from "@/hooks/PmpHooks.js";
import { Editor, Viewer } from "@bytemd/vue-next";
import gfm from "@bytemd/plugin-gfm";
import highlight from "@bytemd/plugin-highlight";
import gemoji from "@bytemd/plugin-gemoji";
import math from "@bytemd/plugin-math-ssr";
import mermaid from "@bytemd/plugin-mermaid";
import "highlight.js/styles/default.css"; // 代码高亮样式
import '@/assets/juejin.css'
import { messageApi, contextHolder } from "@/utils/MessageUtils.js";
// import "juejin-markdown-themes/dist/juejin.min.css"; // 掘金样式

import "bytemd/dist/index.css";

const props = defineProps({
  mainId: {
    type: String,
    default: "",
  },
  relaId:{
    type: String,
    default: "",
  },
  classify:{
    type: String,
    default: () => '',
  },
  canEdit: {
    type: Boolean,
    default: false,
  },
  cb:{
    type:Function,
    default: () => {}
  }
});

const plugins = [
  gfm(),
  highlight(), // 代码高亮插件
  math(), // 数学公式插件
  gemoji(), //  Support Gemoji shortcodes
  mermaid(), // 流程图插件
];

const v = ref("");
const mainName = ref("");
const relaName = ref("");
const canEdit = ref(props.canEdit)
function handleChange(x) {
  v.value = x;
}

const editorConfig = {
  placeholder: "请输入内容...",
};

// 上传图片
async function uploadImages(files) {
  const resultData = [];
  
  const cfg = import.meta.env;
  console.log('====== cfg : ====', cfg)
  const baseURL= cfg.VITE_UPLOAD_BASE_URL
  for (const item of files) {
    const formData = new FormData();
    formData.append("file", item);
    formData.append("folderName", props.id);
    const res = await fetch(`${baseURL}/ass/upload`, {
      method: "POST",
      body: formData,
    });
    const data = await res.json();
    // alert(JSON.stringify(data));
    if (data?.code == "200") {
      // 上传成功后安装指定格式返回
      resultData.push({
        url: data.msg,
        alt: item.name,
        title: item.name,
      });
    } else {
      alert("上传失败");
    }
  }
  return resultData;
}


function changeEditType(){
  canEdit.value = !canEdit.value
}


async function editRelaMd(){

  
  const res = await pmpHooks.editRelaMd(
    props.mainId,
    props.relaId,
    props.classify,
    v.value
  )

  if(res.code == '200'){
    messageApi.success('保存成功')
    props.cb()
  }else{
    messageApi.error('保存失败')
  }

  // alert(JSON.stringify(res))
}

async function loadPageData() {
  // alert(props.id);
  const res = await pmpHooks.queryRelaMd(props.mainId,props.relaId,props.classify);
  v.value = res.msg;

  const mainRes = await pmpHooks.queryPmpItemById(props.mainId);
  // alert(JSON.stringify(res))
  mainName.value = mainRes.result.nameCn;

  const relaRes = await pmpHooks.queryPmpItemById(props.relaId);
  // alert(JSON.stringify(res))
  relaName.value = relaRes.result.nameCn;
  


}
onMounted(async () => {
  await loadPageData();
  //   data.value = pmpHooks.loadPmpDictDetail(props.id)
  //   title.value = pmpHooks.loadPmpDictDetail(props.id).nameCn
});

watch(
  () => props.id,
  async (v) => {
    await loadPageData();
    // data.value = pmpHooks.loadPmpDictDetail(v)
    // title.value = pmpHooks.loadPmpDictDetail(v).nameCn
  }
);
</script>

<style>

.bytemd-fullscreen.bytemd{
  z-index:999999 !important
}
</style>